package com.example.geoaimavlink_android.activity.fragment

import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.geoaimavlink_android.activity.model.MsdkInfoVm
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.ProductManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.StarLinkClientManager
import com.google.gson.Gson

open class BaseFragment : Fragment() {

    protected val gson = Gson();

    protected var mainHandler = Handler(Looper.getMainLooper())

    protected val msdkInfoVm: MsdkInfoVm by activityViewModels()

    protected fun getProduct(): ProductManager? {
        msdkInfoVm.msdkInfo.value?.droneID?.let { droneID ->
            return StarLinkClientManager.getInstance().getProduct(droneID)
        } ?: return null
    }

    protected fun showToast(key: String) {
        mainHandler.post {
            context?.let { context -> Toast.makeText(context, key, Toast.LENGTH_SHORT).show()}
        }
    }

    protected fun format(mJson: String): String? {
        val source = StringBuilder(mJson)
        if (mJson == "") {
            return null
        }
        var offset = 0 //目标字符串插入空格偏移量
        var bOffset = 0 //空格偏移量
        for (i in mJson.indices) {
            when (mJson[i]) {
                '{', '[' -> {
                    bOffset += 4
                    source.insert(i + offset + 1, "\n" + generateBlank(bOffset))
                    offset += bOffset + 1
                }
                ',' -> {
                    source.insert(i + offset + 1, "\n" + generateBlank(bOffset))
                    offset += bOffset + 1
                }
                '}', ']' -> {
                    bOffset -= 4
                    source.insert(i + offset, "\n" + generateBlank(bOffset))
                    offset += bOffset + 1
                }
            }
        }
        return source.toString()
    }

    private fun generateBlank(num: Int): String? {
        val stringBuilder = java.lang.StringBuilder()
        for (i in 0 until num) {
            stringBuilder.append(" ")
        }
        return stringBuilder.toString()
    }
}